<%--
  Created by IntelliJ IDEA.
  User: 14815
  Date: 2022/8/12
  Time: 12:02
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>

<%--获取servlet context 根路径--%>
<%pageContext.setAttribute("APP_PATH", request.getContextPath());%>

<html>
<head>
    <head>
        <meta charset="UTF-8">
        <meta http-equiv="X-UA-Compatible" content="IE=edge">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>XOJ-用户信息</title>

        <link rel="stylesheet" href="${APP_PATH}/templates/sys/css/base.css">
        <link rel="stylesheet" href="${APP_PATH}/templates/sys/css/common.css">
        <link rel="stylesheet" href="${APP_PATH}/templates/user/css/userInfo.css">
        <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet"
              crossorigin="anonymous">

        <!-- 显示ico -->
        <link rel="shorcut icon" href="${APP_PATH}/static/images/logo.ico" type="image/x-ixon">

        <%--引入jquery--%>
        <script type="text/javascript" src="${APP_PATH}/static/js/jquery-3.6.0.js"></script>
        <!-- 引入Bootrstap ui框架 -->
        <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js"
                crossorigin="anonymous"></script>

        <script text="text/javascript">
            $(function () {

                // 定时器
                var count = 5

                // 获取token
                var token = window.localStorage.getItem("token")
                // console.log(token)

                // 获取用户头像
                var path = ''
                // 如果能从数据库获取到用户头像，则将路径展示给变量path，不能则使用默认值
                $.ajax({
                    url: '${APP_PATH}/user/getUserInfoByToken',
                    type: 'GET',
                    data: {
                        "token": token,
                    },
                    beforeSend: function (XMLHttpRequest) {
                        XMLHttpRequest.setRequestHeader("X-Auth0-Token", token);
                    },
                    success: function (res) {
                        // console.log(res)
                        if (res.code === 100) {
                            path = res.extend.userInfo.avatar
                            // console.log(path)
                            if (path == 0) {
                                // console.log(path)
                                // 如果path等于空，说明没有头像信息，显示默认头像
                                $("#userAvatar").attr("src", "${APP_PATH}/static/images/defaultUserAvatar.jpg")
                            } else {
                                // 如果不为空，则显示path路径下的信息
                                $("#userAvatar").attr("src", "${APP_PATH}/static/userImg/"+path)
                            }

                            // 将查出来的数据赋值给table表格中的输入框
                            $("#username").attr("value", res.extend.userInfo.username)
                            $("#password").attr("value", res.extend.userInfo.password)
                            $("#email").attr("value", res.extend.userInfo.email)
                            $("#signature").attr("value", res.extend.userInfo.signature)
                            $("#realname").attr("value", res.extend.userInfo.realname)
                            $("#sex").attr("value", res.extend.userInfo.gender === "male" ? "男" : "女")
                            $("#blogAddress").attr("value", res.extend.userInfo.blog)
                            $("#githubAddress").attr("value", res.extend.userInfo.github)

                            // 更新展示的个性签名
                            var signatureContent = res.extend.userInfo.signature
                            if (signatureContent == null) {
                                $("#signatureP").text('世界上只有10种人，一种懂二进制，一种不懂。')
                            } else {
                                $("#signatureP").text(res.extend.userInfo.signature)
                            }

                        } else {
                            alert(res.extend.error)
                        }
                    }
                })

                // 用户鼠标移入头像范围可以选择重新上传或者设置头像
                $("#userImg").hover(function () {
                    $("#updateUserImg").css("visibility", "visible");
                }, function () {
                    $("#updateUserImg").css("visibility", "hidden");
                })

                // 用户点击更新头像，发送请求去修改后端数据库的图片位置信息
                // 这里使用绝对定位的方式让input框和图片重叠，将input隐藏，点击头像就是点击input输入框，打开文件选择框
                // ajax发送请求时需要携带token，在后端的过滤器中对获取请求头，完成用户登录验证

                $("#inputselect").change(function() {

                    $(".loading").show()

                    // 【0】表示转换为原生的dom对象，使用files属性访问文件列表
                    var files = $('#inputselect')[0].files;
                    const formData = new FormData();
                    formData.append('avatar', files[0])
                    formData.append("token", token)

                    // console.log("formData内容：" + formData)

                    $.ajax({
                        type: 'POST',
                        url: '${APP_PATH}/common/upload',
                        data: formData,
                        // 自定义请求头参数，返回token值
                        beforeSend: function (XMLHttpRequest) {
                            XMLHttpRequest.setRequestHeader("X-Auth0-Token", token);
                        },
                        processData: false,
                        contentType: false,
                        success: function (res) {
                            // alert("res" + res)
                            // 后端返回一个文件名，组装请求路径，获取图片文件名展示到img中
                            if (res.code === 100) {
                                path = res.extend.filename
                            } else {
                                // 弹出提示框
                                alert("因为网络原因，图片上传失败！")
                            }
                        }
                    })

                    // 文件上传完成后加载图片消失
                    // 等待几秒，服务器完成图片上传
                    let timer = setInterval(function () {
                        count --;
                        if (count === 0) {
                            clearInterval(timer)
                            $('.loading').hide()
                            $("#userAvatar").attr("src", "${APP_PATH}/static/userImg/"+path)
                        }
                    }, 1000)
                })

                // 用户信息更新功能
                $("#submitBtn").click(function () {
                    // 先获取table表格中的值
                    var username = $("#username").val()
                    var password = $("#password").val()
                    var email = $("#email").val()
                    var signature = $("#signature").val()
                    var realname = $("#realname").val()
                    var sex = $("#sex").val() === "男" ? "male" : "female"
                    var blog = $("#blogAddress").val()
                    var github = $("#githubAddress").val()

                    // 发送请求将用户信息发送到后端
                    $.ajax({
                        url: '${APP_PATH}/user/changeUserInfo',
                        type: "POST",
                        data: {
                            "username" : username,
                            "password" : password,
                            "email" : email,
                            "signature" : signature,
                            "realname" : realname,
                            "gender" : sex,
                            "blog" : blog,
                            "github" : github,
                        },
                        beforeSend: function (XMLHttpRequest) {
                            XMLHttpRequest.setRequestHeader("X-Auth0-Token", token);
                        },
                        success: function (res) {
                            if (res.code === 100) {
                                // 刷新当前页面
                                window.location.reload()
                            } else {
                                alert("数据更新失败！请稍后再试")
                            }
                        }

                    })
                })

                // 点击返回上一页
                $(".goback").click(function () {
                    window.location.href="${APP_PATH}/templates/sys/questionBank/index.jsp";
                })

            })

        </script>
    </head>
<body>
<div class="index wrapper">
    <div class="left">
        <img class="goback" src="${APP_PATH}/static/images/goback.jpg" alt="">
        <div id="userImg">
            <img id="userAvatar" src="" alt="用户头像">
            <span id="updateUserImg">
                更新头像
                <input id="inputselect" type="file">
            </span>
            <img src="${APP_PATH}/static/images/loading.gif" class="loading" style="display: none;"/>
        </div>
        <div class="signature">
            <p id="signatureP">

            </p>
        </div>
    </div>

    <div class="right">
        <h2>个人信息</h2>
        <div>
            <table class="table table-hover _myTables">
                <tbody>
                <tr>
                    <td>用户名</td>
                    <td>
                        <input id="username" type="text" value="">
                    </td>
                </tr>
                <tr>
                    <td>登录密码</td>
                    <td>
                        <input id="password" type="password" value="">
                    </td>
                </tr>
                <tr>
                    <td>邮箱</td>
                    <td>
                        <input id="email" type="text" value="">
                    </td>
                </tr>
                <tr>
                    <td>个性签名</td>
                    <td>
                        <input id="signature" type="text" value="">
                    </td>
                </tr>
                <tr>
                    <td>真实名字</td>
                    <td>
                        <input id="realname" type="text" value="">
                    </td>
                </tr>
                <tr>
                    <td>性别</td>
                    <td>
                        <input id="sex" type="text" value="">
                </tr>
                <tr>
                    <td>博客地址</td>
                    <td>
                        <input id="blogAddress" type="text" value="">
                    </td>
                </tr>
                <tr>
                    <td>github地址</td>
                    <td>
                        <input id="githubAddress" type="text" value="">
                    </td>
                </tr>
                </tbody>
            </table>
        </div>
        <div class="check">
            <button id="submitBtn">
                提交
            </button>
        </div>
    </div>
</div>
</body>
</html>
